<template>
  <div class="tool-page">
    <div class="tool-header">
      <h1>代码美化工具</h1>
      <p>美化HTML、CSS、JavaScript等代码</p>
    </div>
    
    <div class="code-beautify">
      <div class="form-group">
        <label for="code-type">代码类型：</label>
        <select id="code-type" v-model="codeType" class="form-control">
          <option value="html">HTML</option>
          <option value="css">CSS</option>
          <option value="javascript">JavaScript</option>
          <option value="json">JSON</option>
          <option value="xml">XML</option>
        </select>
      </div>
      
      <div class="form-group">
        <label for="input-code">输入代码：</label>
        <textarea 
          id="input-code" 
          class="form-control code-area" 
          v-model="inputCode" 
          placeholder="在此粘贴需要美化的代码..."
        ></textarea>
      </div>
      
      <div class="actions">
        <button @click="beautifyCode" class="btn primary">美化代码</button>
        <button @click="minifyCode" class="btn secondary">压缩代码</button>
        <button @click="clearCode" class="btn danger">清空</button>
      </div>
      
      <div class="form-group" v-if="outputCode">
        <label for="output-code">美化结果：</label>
        <div class="output-container">
          <pre><code class="output-code">{{ outputCode }}</code></pre>
          <button @click="copyToClipboard" class="btn copy-btn">复制结果</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CodeBeautify',
  data() {
    return {
      codeType: 'javascript',
      inputCode: '',
      outputCode: ''
    }
  },
  methods: {
    beautifyCode() {
      if (!this.inputCode.trim()) {
        alert('请输入需要美化的代码');
        return;
      }
      
      try {
        switch (this.codeType) {
          case 'html':
            this.outputCode = this.beautifyHTML(this.inputCode);
            break;
          case 'css':
            this.outputCode = this.beautifyCSS(this.inputCode);
            break;
          case 'javascript':
            this.outputCode = this.beautifyJS(this.inputCode);
            break;
          case 'json':
            this.outputCode = this.beautifyJSON(this.inputCode);
            break;
          case 'xml':
            this.outputCode = this.beautifyXML(this.inputCode);
            break;
          default:
            this.outputCode = this.inputCode;
        }
      } catch (error) {
        alert(`美化失败: ${error.message}`);
      }
    },
    minifyCode() {
      if (!this.inputCode.trim()) {
        alert('请输入需要压缩的代码');
        return;
      }
      
      try {
        switch (this.codeType) {
          case 'html':
            this.outputCode = this.minifyHTML(this.inputCode);
            break;
          case 'css':
            this.outputCode = this.minifyCSS(this.inputCode);
            break;
          case 'javascript':
            this.outputCode = this.minifyJS(this.inputCode);
            break;
          case 'json':
            this.outputCode = this.minifyJSON(this.inputCode);
            break;
          case 'xml':
            this.outputCode = this.minifyXML(this.inputCode);
            break;
          default:
            this.outputCode = this.inputCode;
        }
      } catch (error) {
        alert(`压缩失败: ${error.message}`);
      }
    },
    clearCode() {
      this.inputCode = '';
      this.outputCode = '';
    },
    copyToClipboard() {
      if (!this.outputCode) return;
      
      navigator.clipboard.writeText(this.outputCode)
        .then(() => {
          alert('已复制到剪贴板');
        })
        .catch(err => {
          console.error('无法复制到剪贴板:', err);
        });
    },
    
    // 简单的代码美化实现
    // 实际项目中应使用专业的代码美化库如js-beautify, prettier等
    
    beautifyHTML(code) {
      // 简单的HTML美化逻辑
      let formatted = '';
      let indent = 0;
      
      // 将标签分行并添加缩进
      code = code.replace(/>\s*</g, '>\n<');
      
      const lines = code.split('\n');
      
      for (let i = 0; i < lines.length; i++) {
        let line = lines[i].trim();
        
        if (line.match(/<\/[^>]+>/)) {
          // 闭合标签，减少缩进
          indent--;
        }
        
        if (indent >= 0) {
          formatted += '  '.repeat(indent) + line + '\n';
        } else {
          indent = 0;
          formatted += line + '\n';
        }
        
        if (line.match(/<[^\/][^>]*[^\/]>/) && !line.match(/<\/[^>]+>/) && !line.match(/\/>/)) {
          // 开放标签，增加缩进
          indent++;
        }
      }
      
      return formatted;
    },
    
    beautifyCSS(code) {
      // 简单的CSS美化逻辑
      code = code.replace(/\s*{\s*/g, ' {\n  ');
      code = code.replace(/\s*;\s*/g, ';\n  ');
      code = code.replace(/\s*}\s*/g, '\n}\n\n');
      code = code.replace(/\n\s*\n/g, '\n');
      return code;
    },
    
    beautifyJS(code) {
      // 简单的JS美化逻辑
      // 实际项目中应使用专业库
      try {
        // 尝试使用JSON.parse和JSON.stringify美化
        const obj = eval('(' + code + ')');
        return JSON.stringify(obj, null, 2);
      } catch (e) {
        // 如果不是有效的JSON，使用简单的替换
        code = code.replace(/{\s*/g, '{\n  ');
        code = code.replace(/;\s*/g, ';\n  ');
        code = code.replace(/}\s*/g, '\n}\n\n');
        return code;
      }
    },
    
    beautifyJSON(code) {
      // JSON美化
      const obj = JSON.parse(code);
      return JSON.stringify(obj, null, 2);
    },
    
    beautifyXML(code) {
      // 简单的XML美化，类似HTML
      return this.beautifyHTML(code);
    },
    
    minifyHTML(code) {
      // 简单的HTML压缩
      return code
        .replace(/\s+/g, ' ')
        .replace(/>\s+</g, '><')
        .replace(/\s+>/g, '>')
        .replace(/>\s+/g, '>')
        .replace(/\s+=/g, '=')
        .replace(/=\s+/g, '=')
        .trim();
    },
    
    minifyCSS(code) {
      // 简单的CSS压缩
      return code
        .replace(/\/\*[\s\S]*?\*\//g, '') // 移除注释
        .replace(/\s+/g, ' ')
        .replace(/\s*{\s*/g, '{')
        .replace(/\s*;\s*/g, ';')
        .replace(/\s*}\s*/g, '}')
        .replace(/\s*:\s*/g, ':')
        .replace(/\s*,\s*/g, ',')
        .trim();
    },
    
    minifyJS(code) {
      // 简单的JS压缩
      // 实际项目中应使用专业库如UglifyJS
      try {
        // 尝试使用JSON.parse和JSON.stringify压缩
        const obj = eval('(' + code + ')');
        return JSON.stringify(obj);
      } catch (e) {
        // 如果不是有效的JSON，使用简单的替换
        return code
          .replace(/\/\/.*$/gm, '') // 移除单行注释
          .replace(/\/\*[\s\S]*?\*\//g, '') // 移除多行注释
          .replace(/\s+/g, ' ')
          .replace(/\s*{\s*/g, '{')
          .replace(/\s*;\s*/g, ';')
          .replace(/\s*}\s*/g, '}')
          .trim();
      }
    },
    
    minifyJSON(code) {
      // JSON压缩
      const obj = JSON.parse(code);
      return JSON.stringify(obj);
    },
    
    minifyXML(code) {
      // 简单的XML压缩，类似HTML
      return this.minifyHTML(code);
    }
  }
}
</script>

<style scoped>
.code-beautify {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.code-area {
  font-family: monospace;
  min-height: 200px;
  white-space: pre;
}

.actions {
  display: flex;
  gap: 1rem;
}

.output-container {
  position: relative;
  margin-top: 0.5rem;
}

.output-code {
  display: block;
  background-color: #f8f9fa;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  padding: 1rem;
  font-family: monospace;
  white-space: pre-wrap;
  overflow-x: auto;
  max-height: 400px;
  overflow-y: auto;
}

.copy-btn {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  padding: 0.25rem 0.5rem;
  font-size: 0.8rem;
  background-color: rgba(52, 152, 219, 0.1);
  color: var(--primary-color);
}

.copy-btn:hover {
  background-color: rgba(52, 152, 219, 0.2);
}
</style>